import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:like_button/like_button.dart';
import 'package:meco/common/models/chat_room_model.dart';
import 'package:meco/views/index.dart';
import 'dart:io';

import 'index.dart';

class SharePage extends GetView<ShareController> {
  const SharePage({super.key});

  // 主视图
  Widget _buildView() {
    return Stack(
      children: [
        Positioned.fill(child: Image.asset(Images.startBg, fit: BoxFit.fill)),
        SafeArea(
          child: Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Row(
                  children: [
                    SizedBox(width: 119.w),
                    Text(
                      'Burning sharing',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20.sp,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                    Spacer(),
                    GestureDetector(
                      onTap: () {
                        // 获取用户服务
                        final userService = Get.find<UserService>();

                        // 检查登录状态并执行操作
                        userService.checkLoginThenExecute(
                          loginRequiredMessage:
                              'Please login to share your work',
                          onLoggedIn: () {
                            // 已登录，跳转到上传页面
                            Get.toNamed(Routes.upload);
                          },
                        );
                      },
                      child: Icon(
                        IconFontIcons.iconSend,
                        size: 28.sp,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),

                SizedBox(height: 20.h),

                // 滚动列表
                Obx(
                  () =>
                      controller.isLoading.value
                          ? const Center(
                            child: CircularProgressIndicator(
                              color: Colors.white,
                            ),
                          )
                          : SizedBox(
                            height: DeviceInfoUtil.isIPad() ? 370.h : 329.h,
                            child: _buildCeramicList(),
                          ),
                ),

                SizedBox(height: 28.h),

                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    'Popular Group Chat',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20.sp,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ),

                SizedBox(height: 16.h),

                // 热门群聊
                Expanded(
                  child: Obx(
                    () => ListView.builder(
                      itemCount: controller.groupChats.length,
                      itemBuilder: (context, index) {
                        final chatRoom = controller.groupChats[index];
                        return Padding(
                          padding: EdgeInsets.only(bottom: 10.h),
                          child: Container(
                            width: 374.w,
                            height: 96.h,
                            decoration: ShapeDecoration(
                              color: const Color(0xFF305CA9),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12.r),
                              ),
                            ),
                            child: Row(
                              children: [
                                SizedBox(width: 16.w),
                                // 左侧群聊头像组
                                SizedBox(
                                  width: 75.w,
                                  height: 75.h,
                                  child: Stack(
                                    children: [
                                      // 左上角头像
                                      _buildGroupAvatar(
                                        chatRoom,
                                        0,
                                        Offset(0, 0),
                                      ),
                                      // 右上角头像
                                      _buildGroupAvatar(
                                        chatRoom,
                                        1,
                                        Offset(39.w, 0),
                                      ),
                                      // 左下角头像
                                      _buildGroupAvatar(
                                        chatRoom,
                                        2,
                                        Offset(0, 39.h),
                                      ),

                                      // 中间的图标
                                      Positioned(
                                        left: 27.5.w,
                                        top: 27.5.h,
                                        child: Center(
                                          child: Icon(
                                            Icons.add,
                                            size: 20.sp,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),

                                      // 右下角剩余人数
                                      chatRoom.memberIds.length > 4
                                          ? Positioned(
                                            right: 0,
                                            bottom: 0,
                                            child: Container(
                                              width: 36.w,
                                              height: 36.h,
                                              decoration: BoxDecoration(
                                                color: const Color(0xFF4169B8),
                                                shape: BoxShape.circle,
                                                border: Border.all(
                                                  color: Colors.white,
                                                  width: 2,
                                                ),
                                              ),
                                              child: Center(
                                                child: Text(
                                                  '+${chatRoom.memberIds.length - 3}',
                                                  style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 12.sp,
                                                    fontWeight: FontWeight.w500,
                                                  ),
                                                ),
                                              ),
                                            ),
                                          )
                                          : _buildGroupAvatar(
                                            chatRoom,
                                            3,
                                            Offset(39.w, 39.h),
                                          ),
                                    ],
                                  ),
                                ),

                                SizedBox(width: 16.w),

                                // 群聊名称
                                Expanded(
                                  child: Text(
                                    chatRoom.name,
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 14.sp,
                                      fontFamily: 'Inter',
                                      fontWeight: FontWeight.w600,
                                      height: 1.43,
                                    ),
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),

                                SizedBox(width: 10.w),

                                // Join In按钮
                                GestureDetector(
                                  onTap:
                                      () => controller.joinGroupChat(
                                        chatRoom.id!,
                                      ),
                                  child: Container(
                                    width: 90.w,
                                    height: 40.h,
                                    decoration: ShapeDecoration(
                                      gradient: LinearGradient(
                                        begin: Alignment(0.50, -0.00),
                                        end: Alignment(0.50, 1.00),
                                        colors: [
                                          const Color(0xFF4580DD),
                                          const Color(0xFF5592F1),
                                        ],
                                      ),
                                      shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(
                                          37.r,
                                        ),
                                      ),
                                    ),
                                    child: Center(
                                      child: Text(
                                        'join in',
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 16.sp,
                                          fontWeight: FontWeight.w400,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),

                                SizedBox(width: 16.w),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  // 烧制陶瓷卡片列表
  Widget _buildCeramicList() {
    if (controller.completedCeramics.isEmpty) {
      return Center(
        child: Text(
          'There is no completed ceramic',
          style: TextStyle(color: Colors.white, fontSize: 16.sp),
        ),
      );
    }

    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: controller.completedCeramics.length,
      padding: EdgeInsets.symmetric(vertical: 10.h),
      itemBuilder: (context, index) {
        final ceramic = controller.completedCeramics[index];
        return Padding(
          padding: EdgeInsets.only(right: 16.w),
          child: _buildCeramicCard(ceramic),
        );
      },
    );
  }

  // 构建群聊头像
  Widget _buildGroupAvatar(ChatRoom chatRoom, int index, Offset offset) {
    // 如果索引超出成员数量，返回空容器
    if (index >= chatRoom.memberIds.length) {
      return Container();
    }

    // 获取用户ID
    final userId = chatRoom.memberIds[index];
    // 获取用户信息
    final user = controller.chatUserCache[userId];

    return Positioned(
      left: offset.dx,
      top: offset.dy,
      child: Container(
        width: 36.w,
        height: 36.h,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(color: Colors.white, width: 2),
          image: DecorationImage(
            image:
                user?.avatar != null
                    ? AssetImage(user!.avatar!)
                    : AssetImage(Images.avatar1),
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  // 烧制陶瓷卡片
  Widget _buildCeramicCard(Ceramic ceramic) {
    final user = controller.userCache[ceramic.userId];
    final isFollowing = controller.followStatusCache[ceramic.userId] ?? false;
    final isLiked = controller.likeStatusCache[ceramic.id!] ?? false;
    final isFavorited = controller.favoriteStatusCache[ceramic.id!] ?? false;

    return Container(
      width: 325.w,
      decoration: ShapeDecoration(
        color: const Color(0xFF305CA9),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12.r),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.only(left: 14.w, right: 32.w, top: 14.h),
            child: Row(
              children: [
                // 用户头像
                GestureDetector(
                  onTap: () {
                    // 先尝试删除已存在的MeController实例，再跳转
                    try {
                      if (Get.isRegistered<MeController>()) {
                        Get.delete<MeController>(force: true);
                      }
                    } catch (e) {
                      print('删除MeController失败: $e');
                    }
                    Get.toNamed(
                      Routes.me,
                      arguments: {
                        'userId': user?.id,
                        'fromNavBar': false,
                        'forceRefresh': true,
                      },
                    );
                  },
                  child: CircleAvatar(
                    radius: 22.r,
                    backgroundImage:
                        user?.avatar != null
                            ? AssetImage(user!.avatar!)
                            : AssetImage(Images.avatar1),
                  ),
                ),
                SizedBox(width: 6.w),
                // 用户名
                Text(
                  user?.nickname ?? user?.username ?? 'Unknown',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(width: 10.w),
                // 关注按钮
                GestureDetector(
                  onTap: () => _handleFollow(ceramic.userId),
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 6.w,
                      vertical: 3.h,
                    ),
                    decoration: BoxDecoration(
                      color: isFollowing ? Colors.transparent : Colors.white,
                      borderRadius: BorderRadius.circular(12.r),
                      border:
                          isFollowing
                              ? Border.all(color: Colors.white, width: 1)
                              : null,
                    ),
                    child: Row(
                      children: [
                        Icon(
                          isFollowing ? Icons.check : Icons.add,
                          size: 16.sp,
                          color:
                              isFollowing
                                  ? Colors.white
                                  : const Color(0xFF0A3D8E),
                        ),
                        Text(
                          isFollowing ? 'Followed' : 'Follow',
                          style: TextStyle(
                            color:
                                isFollowing
                                    ? Colors.white
                                    : const Color(0xFF0A3D8E),
                            fontSize: 12.sp,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Spacer(),
                // 收藏
                LikeButton(
                  size: 24.sp,
                  isLiked: isFavorited,
                  animationDuration: Duration(milliseconds: 800),
                  circleColor: CircleColor(
                    start: Color(0xFFFF5722),
                    end: Color(0xFFFFC107),
                  ),
                  bubblesColor: BubblesColor(
                    dotPrimaryColor: Color(0xFFFF5722),
                    dotSecondaryColor: Color(0xFFFFC107),
                    dotThirdColor: Color(0xFFFF9800),
                    dotLastColor: Color(0xFFF44336),
                  ),
                  likeBuilder: (bool isLiked) {
                    return Icon(
                      isLiked
                          ? IconFontIcons.iconLikeFill
                          : IconFontIcons.iconLike,
                      color: isLiked ? Colors.red : Colors.white,
                      size: 24.sp,
                    );
                  },
                  onTap: (isLiked) async {
                    await _handleFavorite(ceramic.id!);
                    return controller.favoriteStatusCache[ceramic.id!] ?? false;
                  },
                ),
                SizedBox(width: 27.w),
                // 点赞
                LikeButton(
                  size: 24.sp,
                  isLiked: isLiked,
                  animationDuration: Duration(milliseconds: 800),
                  circleColor: CircleColor(
                    start: Color(0xFF00DDFF),
                    end: Color(0xFF0099CC),
                  ),
                  bubblesColor: BubblesColor(
                    dotPrimaryColor: Color(0xFF33B5E5),
                    dotSecondaryColor: Color(0xFF0099CC),
                    dotThirdColor: Color(0xFF00DDFF),
                    dotLastColor: Color(0xFF00AACC),
                  ),
                  likeBuilder: (bool isLiked) {
                    return Icon(
                      isLiked
                          ? IconFontIcons.iconGoodFill
                          : IconFontIcons.iconGood,
                      color: isLiked ? Colors.red : Colors.white,
                      size: 24.sp,
                    );
                  },
                  onTap: (isLiked) async {
                    await _handleLike(ceramic.id!);
                    return controller.likeStatusCache[ceramic.id!] ?? false;
                  },
                ),
              ],
            ),
          ),
          // 陶瓷描述
          GestureDetector(
            onTap: () {
              Get.toNamed(Routes.detail, arguments: {'ceramic': ceramic});
            },
            child: Padding(
              padding: EdgeInsets.only(left: 14.w, right: 14.w, top: 10.h),
              child: Text(
                ceramic.description ?? 'There is no description',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 15.sp,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w400,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          Spacer(),
          // 陶瓷图片
          GestureDetector(
            onTap: () {
              Get.toNamed(Routes.detail, arguments: {'ceramic': ceramic});
            },
            child: Container(
              padding: EdgeInsets.only(top: 10.h, right: 14.w),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(12.r),
                child:
                    ceramic.imageUrl != null
                        ? ceramic.imageUrl!.startsWith('/')
                            ? Image.file(
                              File(ceramic.imageUrl!),
                              fit: BoxFit.fill,
                              errorBuilder: (context, error, stackTrace) {
                                print('图片加载错误: $error');
                                return Image.asset(
                                  Images.ceramic1,
                                  fit: BoxFit.fill,
                                );
                              },
                            )
                            : Image.asset(
                              ceramic.imageUrl!,
                              fit: BoxFit.fill,
                              errorBuilder: (context, error, stackTrace) {
                                return Image.asset(
                                  Images.ceramic1,
                                  fit: BoxFit.fill,
                                );
                              },
                            )
                        : Image.asset(Images.ceramic1, fit: BoxFit.fill),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 处理关注操作
  Future<void> _handleFollow(int userId) async {
    // 获取用户服务
    final userService = Get.find<UserService>();

    // 检查登录状态并执行操作
    userService.checkLoginThenExecute(
      loginRequiredMessage: 'You need to login to follow this user',
      onLoggedIn: () {
        // 已登录，执行关注操作
        final currentUserId = userService.currentUser.value!.id!;

        // 不能关注自己
        if (currentUserId == userId) {
          Get.snackbar('Error', 'You cannot follow yourself');
          return;
        }

        // 执行关注/取消关注操作
        controller.toggleFollow(userId);
      },
    );
  }

  // 处理点赞操作
  Future<void> _handleLike(int ceramicId) async {
    // 获取用户服务
    final userService = Get.find<UserService>();

    // 检查登录状态并执行操作
    userService.checkLoginThenExecute(
      loginRequiredMessage: 'You need to login to like this work',
      onLoggedIn: () {
        // 已登录，执行点赞操作
        controller.toggleLike(ceramicId);
      },
    );
  }

  // 处理收藏操作
  Future<void> _handleFavorite(int ceramicId) async {
    // 获取用户服务
    final userService = Get.find<UserService>();

    // 检查登录状态并执行操作
    userService.checkLoginThenExecute(
      loginRequiredMessage: 'You need to login to collect this work',
      onLoggedIn: () {
        // 已登录，执行收藏操作
        controller.toggleFavorite(ceramicId);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ShareController>(
      init: ShareController(),
      id: "share",
      builder: (_) {
        return Scaffold(body: _buildView());
      },
    );
  }
}
